package com.yin.reactor.service;

import com.yin.reactor.entity.User;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * UserServiceImpl
 *
 * @author Yin Guiqing
 */
@Service
public class UserServiceImpl implements UserService {
    // 为了方便，这里使用 Map 代替数据库存储数据
    private final Map<Integer, User> map = new HashMap<>();

    public UserServiceImpl() {
        this.map.put(1, new User(1, "Alice", 'F', 18));
        this.map.put(2, new User(2, "Bella", 'F', 20));
        this.map.put(3, new User(3, "Cindy", 'F', 18));
        this.map.put(4, new User(4, "Diana", 'F', 20));
        this.map.put(5, new User(5, "Emily", 'F', 18));
    }

    @Override
    public Mono<User> getUserById(int id) {
        return Mono.justOrEmpty(this.map.get(id));
    }

    @Override
    public Flux<User> getAllUsers() {
        return Flux.fromIterable(this.map.values());
    }

    @Override
    public Mono<Void> saveUser(Mono<User> userMono) {
        return userMono.doOnNext(user -> map.put(user.getId(), user))
                .thenEmpty(Mono.empty());
    }
}
